package com.speaktoitcookbook.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.json.JSONArray;

import com.speaktoitcookbook.bean.DishStep;
import com.speaktoitcookbook.dao.IDishStepDao;
import com.speaktoitcookbook.dao.factory.DaoFactory;
import com.speaktoitcookbook.db.Database;
import com.speaktoitcookbook.util.DBUtil;
import com.speaktoitcookbook.util.LogUtil;

@WebServlet("/CookMethodService")
public class CookMethodService extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final Logger log = LogUtil
            .getLogger(CookMethodService.class);
    int cbID = 1;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");

        cbID = request.getParameter("cb") == null ? 0 : Integer
                .parseInt(request.getParameter("cb"));

        PrintWriter out = response.getWriter();

        IDishStepDao dishstepDao = DaoFactory.getDishStepDao();
        DishStep dishstep = new DishStep();
        dishstep.setID(cbID);
        List<DishStep> dishsteplist = null;

        try {
            dishsteplist = dishstepDao.getDishStep(cbID);
        } catch (SQLException e) {
        } catch (Exception e) {
            e.printStackTrace();
        }

        log.info("做法步骤：" + dishsteplist);
        JSONArray newsjson = new JSONArray(dishsteplist, false);
        out.print(newsjson.toString());
        out.flush();
        out.close();

        String sql = "UPDATE `tb_cookbook` SET `dishHits`=(`dishHits`+1) WHERE `cbID`=?";
        Connection conn = Database.getConnection();
        boolean result = false;
        try {
            result = DBUtil.execute(conn, sql, "" + cbID);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        log.info("点击数增加：" + result);
    }

}